﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using WorkFlowSystem.Common;
using WorkFlowSystem.DataBase;
using DevComponents.DotNetBar.Controls;

namespace WorkFlowSystem
{
    public partial class DepartmentEditUi : Form
    {
        public DepartmentEditUi()
        {
            InitializeComponent();
            m_modify_mode = false;
        }

        #region 辅助方法
        public void SetMode(bool modify_mode, int did)
        {
            m_modify_mode = modify_mode;
            if (m_dpt_info == null)
            {
                m_dpt_info = new DepartmentInfo();
                m_dpt_info.did = did;
            }
        }

        private void DepartmentEditUi_Load(object sender, EventArgs e)
        {
            comboBoxEx1.Items.Add("-");
            comboBoxEx1.SelectedIndex = 0;
            if (m_modify_mode)
            {
                if (init_modify_dpt() < 0)
                    this.Close();
            }
            else
            {
                if (init_add_dpt() < 0)
                    this.Close();
            }
        }

        private int load_dpt()
        {
            Logger.WriteLog("enter load_dpt");
            get_d_name();
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }

            //获取did部门的部门信息
            string sql = "select * from department where did=@did";
            DataTable dt = new DataTable();
            List<SqlParameter> para_list = new List<SqlParameter>();
            para_list.Add(new SqlParameter("@did", m_dpt_info.did));
            if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
            {
                Logger.WriteLogError("get department info of [" + m_dpt_info.did + "] fail");
                db_op.CloseDB();
                return -1;
            }
            m_dpt_info.d_name = dt.Rows[0]["d_name"].ToString();
            m_dpt_info.description = dt.Rows[0]["d_description"].ToString();
            try
            {
                string d_parent = dt.Rows[0]["d_parent"].ToString();
                if (d_parent != "")
                    m_dpt_info.parent_did = int.Parse(dt.Rows[0]["d_parent"].ToString());
                else
                    m_dpt_info.parent_did = -1;
            }
            catch (Exception ex)
            {
                Logger.WriteLogError("parse parent_did[" + dt.Rows[0]["d_parent"].ToString() + "] to int fail[" + ex.Message + "]");
                db_op.CloseDB();
                return -1;
            }

            //获取did部门的上级部门名
            if (m_dpt_info.parent_did > 0)
            {
                sql = "select d_name from department where did=@parent_did";
                dt.Clear();
                para_list.Clear();
                para_list.Add(new SqlParameter("@parent_did", m_dpt_info.parent_did));
                if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
                {
                    Logger.WriteLogError("get parent_did[" + m_dpt_info.parent_did + "] fail");
                    db_op.CloseDB();
                    return -1;
                }
                db_op.CloseDB();
                m_dpt_info.parent_d_name = dt.Rows[0]["d_name"].ToString();
            }
            return 0;
        }

        private int init_add_dpt()
        {
            if (get_d_name() < 0)
            {
                MessageBox.Show("获取部门名称失败");
                return -1;
            }
            return 0;
        }

        private int init_modify_dpt()
        {
            //load data from database to memory
            if (load_dpt() < 0)
            {
                MessageBox.Show("加载部门信息失败");
                return -1;
            }
            //init控件
            textBoxX1.Text = m_dpt_info.d_name;
            comboBoxEx1.SelectedIndex = (comboBoxEx1.Items.IndexOf(m_dpt_info.parent_d_name) < 0) ? 0 : comboBoxEx1.Items.IndexOf(m_dpt_info.parent_d_name);
            richTextBoxEx1.Text = m_dpt_info.description;
            return 0;
        }

        private int get_d_name()
        {
            Logger.WriteLog("enter get_d_name");
            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return -1;
            }
            string sql = "select d_name from department";
            DataTable dt = new DataTable();
            if (db_op.ExecuteDataTable(sql, null, false, ref dt) < 0)
            {
                Logger.WriteLogError("get department d_name fail");
                db_op.CloseDB();
                return -1;
            }
            db_op.CloseDB();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                comboBoxEx1.Items.Add(dt.Rows[i]["d_name"].ToString());
            }
            return 0;
        }
        #endregion

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX1_Click(object sender, EventArgs e)
        {
            RetCode rt = validator(textBoxX1.Text);

            switch (rt)
            { 
                case RetCode.MSG_GROUP_NAME_LENGTH_20_D:
                    MessageBox.Show("请输入1-20个字符");
                    break;
                case RetCode.MSG_GROUP_UPDATE_SUCCESS:
                    MessageBox.Show("部门修改成功");
                    if (OnChange != null)
                        OnChange(sender, e);
                    this.Close();
                    break;
                case RetCode.MSG_GROUP_ADD_SUCCESS:
                    MessageBox.Show("部门添加成功");
                    if (OnChange != null)
                        OnChange(sender, e);
                    this.Close();
                    break;
                case RetCode.MSG_UNKNOWN:
                    break;
                default:
                    Logger.WriteLogError("un-expected error [" + rt.ToString() + "]");
                    break;
            }
        }

        /// <summary>
        /// 清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX2_Click(object sender, EventArgs e)
        {
            Common.CommonDefine.clear_values(this.panelEx1);
            comboBoxEx1.SelectedIndex = 0;
        }

        /// <summary>
        /// 删除——当部门下有员工，有职位，有子部门时，不可以删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonX3_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除?", "删除部门", MessageBoxButtons.OKCancel);
            if (dr == DialogResult.OK)
            {
                int did = m_dpt_info.did;
                DBOperator db_op = new DBOperator();
                if (db_op.ConnectDB() < 0)
                {
                    MessageBox.Show("无法连接服务器，请检查网络连接");
                    return;
                }
                List<SqlParameter> para_list = new List<SqlParameter>();
                string sql = "declare @user_count int;\n";
                sql += "declare @position_count int;\n";
                sql += "declare @department_count int;\n";
                sql += "select @user_count=COUNT(*) from user_info where u_did=@did;\n";
                sql += "select @position_count=COUNT(*) from position_info where p_did=@did;\n";
                sql += "select @department_count=COUNT(*) from department where d_parent=@did;\n";
                sql += "if  @user_count = 0 and @position_count=0 and @department_count = 0\n" +
                    "delete from department where did=@did or d_parent=@did";
                para_list.Add(new SqlParameter("@did", did));
                if (db_op.ExecuteNonQuery(sql, para_list, true) < 0)
                {
                    Logger.WriteLogError("delete department of [" + did + "]fail");
                    MessageBox.Show("删除失败 请先删除该部门下的员工,职位,子部门");
                }
                db_op.CloseDB();
                //send event to HomeUi to refresh datagridview
                if (OnChange != null)
                    OnChange(sender, e);
                this.Close();
            }
        }

        private int is_valid_department(string d_name, string parent_dpt)
        {
            if (d_name == parent_dpt)
            {
                //判断选择的上级部门是否为当前部门
                MessageBox.Show("上级部门不能为当前部门");
                return -1;
            }
            else
            {
                //判断选择的上级部门是否为当前部门的子部门
                DBOperator db_op = new DBOperator();
                if (db_op.ConnectDB() < 0)
                {
                    MessageBox.Show("无法连接服务器，请检查网络连接");
                    return -1;
                }

                string sql = "select * from department where d_name=@dname and d_parent=(select did from department where d_name=@dname2)"; ;
                DataTable dt = new DataTable();
                List<SqlParameter> para_list = new List<SqlParameter>();

                para_list.Add(new SqlParameter("@dname", parent_dpt));
                para_list.Add(new SqlParameter("@dname2", d_name));
                if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
                {
                    MessageBox.Show("获取部门信息失败");
                    db_op.CloseDB();
                    return -1;
                }
                if (dt.Rows.Count > 0) {
                    MessageBox.Show("上级部门不能为当前部门的子部门");
                    db_op.CloseDB();
                    return -1;
                }
                db_op.CloseDB();
            }
            return 0;
        }

        private RetCode validator(string d_name)
        {
            RetCode rt = RetCode.MSG_UNKNOWN;
            if (!CommonValidate.inputLenValidate(d_name, 1, 20))
                return RetCode.MSG_GROUP_NAME_LENGTH_20_D;

            string parent_dpt = comboBoxEx1.SelectedItem.ToString();

            if (is_valid_department(d_name, parent_dpt) < 0)
            {
                Logger.WriteLogError("invalid parent department");
                return RetCode.MSG_UNKNOWN;
            }

            m_dpt_info.d_name = d_name;
            m_dpt_info.parent_d_name = parent_dpt;
            m_dpt_info.description = richTextBoxEx1.Text;

            DBOperator db_op = new DBOperator();
            if (db_op.ConnectDB() < 0)
            {
                MessageBox.Show("无法连接服务器，请检查网络连接");
                return RetCode.MSG_UNKNOWN;
            }

            string sql = "";
            DataTable dt = new DataTable();
            List<SqlParameter> para_list = new List<SqlParameter>();

            if (parent_dpt != "-")
            {
                //获取did部门的上级部门ID
                sql = "select did from department where d_name=@parent_d_name";
                para_list.Add(new SqlParameter("@parent_d_name", m_dpt_info.parent_d_name));
                if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
                {
                    Logger.WriteLogError("get parent department's did of[" + m_dpt_info.parent_d_name + "] fail");
                    MessageBox.Show("获取部门信息失败");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
                try
                {
                    m_dpt_info.parent_did = int.Parse(dt.Rows[0]["did"].ToString());
                }
                catch (Exception ex)
                {
                    Logger.WriteLogError("parse parent_did[" + dt.Rows[0]["did"].ToString() + "] to int fail[" + ex.Message + "]");
                    MessageBox.Show("获取部门信息失败");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
            }
            else
                m_dpt_info.parent_did = 0;

            if (m_modify_mode)
            {
                sql = "update department set d_name=@d_name, d_parent=@d_parent, d_description=@d_description, d_update_uid=@d_update_uid, d_update_date=@d_update_date " +
                    "where did=@did";
            }
            else
            {
                //判断部门是否已存在
                dt.Clear();
                sql = "select * from Department where d_name=@d_name";
                para_list.Add(new SqlParameter("@d_name", m_dpt_info.d_name));
                Logger.WriteSqlLog(sql, para_list);
                if (db_op.ExecuteDataTable(sql, para_list, false, ref dt) < 0)
                {
                    Logger.WriteLogError("get department info of[" + m_dpt_info.d_name + "] fail");
                    MessageBox.Show("获取部门信息失败");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
                if (dt.Rows.Count > 0)
                {
                    MessageBox.Show("部门已存在");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
                sql = "insert into department(d_name, d_parent, d_description, d_insert_uid, d_insert_date) values(@d_name, @d_parent, @d_description, @d_insert_uid, @d_insert_date)";
            }
            para_list.Clear();
            para_list.Add(new SqlParameter("@did", m_dpt_info.did));
            para_list.Add(new SqlParameter("@d_name", m_dpt_info.d_name));
            para_list.Add(new SqlParameter("@d_parent", m_dpt_info.parent_did));
            para_list.Add(new SqlParameter("@d_description", m_dpt_info.description));
            para_list.Add(new SqlParameter("@d_insert_uid", CurrentUser.user_id));
            para_list.Add(new SqlParameter("@d_insert_date", DateTime.Now));
            para_list.Add(new SqlParameter("@d_update_uid", CurrentUser.user_id));
            para_list.Add(new SqlParameter("@d_update_date", DateTime.Now));
            if (db_op.ExecuteNonQuery(sql, para_list, false) < 0)
            {
                if (m_modify_mode)
                {
                    Logger.WriteLogError("modify department fail");
                    MessageBox.Show("修改部门信息失败");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
                else
                {
                    Logger.WriteLogError("add department fail");
                    MessageBox.Show("添加部门信息失败");
                    db_op.CloseDB();
                    return RetCode.MSG_UNKNOWN;
                }
            }
            else
            {
                if (m_modify_mode)
                {
                    rt = RetCode.MSG_GROUP_UPDATE_SUCCESS;
                }
                else
                {
                    rt = RetCode.MSG_GROUP_ADD_SUCCESS;
                }
            }
            db_op.CloseDB();
            return rt;
        }

        public delegate void DepartmentChange(object sender, EventArgs e);
        public event DepartmentChange OnChange;
        private DepartmentInfo m_dpt_info;
        private bool m_modify_mode;
    }

    class DepartmentInfo
    {
        public DepartmentInfo()
        {
            did = -1;
            d_name = "";
            parent_did = 0;
            parent_d_name = "";
            description = "";
        }

        public int did;
        public string d_name;
        public int parent_did;
        public string parent_d_name;
        public string description;
    }
}
